<template>
    <el-dialog :model-value="dialogVisible" title="新增科目维度" width="800px" :before-close="handleClose" append-to-body>
        <el-form ref="formRef" :model="dataForm" label-width="10px"  :inline="false">
            <el-form-item prop="subjectName" style="padding:10px;margin-bottom:10px" label="已选科目：" label-width="100px">
                <div v-if="selectSubjectList.length > 0" style="margin:0">
                    <el-tag v-for="(item, index) in selectSubjectList" :key="index" class="tags" closable
                        :type="item.label" @close="removeTab(index, item)">
                        {{ item.categoryName }}
                    </el-tag>
                </div>
                <div class="no-data" style="margin:0" v-else>暂无数据</div>
            </el-form-item>
            <el-form-item>
                <el-row style="width:100%;border:1px solid #dcdfe6;border-radius:5px;">
                    <!-- <el-col :span="12">
                        <div class="head">
                            <p>组织机构</p>
                        </div>
                        <div class="city-box">
                            <el-tree class="filter-tree" node-key="id" :data="treeDatas" :props="CONMPAYN_PROPS"
                                default-expand-all  ref="treeRef" @check="currentChange"
                                show-checkbox :check-strictly="true">
                            </el-tree>
                        </div>
                    </el-col> -->
                    <el-col :span="24">
                        <div class="head">
                            <p>已选 {{ selectNum }}/{{ subjectList.length }}</p>
                            <p @click="allCheck">全选</p>
                        </div>
                        <div class="selec-city">
                            <el-form-item prop="subjectName" style="padding:10px;margin-bottom:10px">
                                <el-input v-model="dataForm.subjectName" placeholder="请输入科目名称搜索" clearable
                                    @input="searchSubject" />
                            </el-form-item>
                            <div class="subject-con">
                                <div v-if="subjectList.length > 0">
                                    <div v-for="(item, index) in subjectList" :key="index" class="subject-list">
                                        <p>{{ item.categoryName }}（{{ item.categoryCode }}）</p>
                                        <div class="check-box" @click="selectSubject(index)">
                                            <img :src="selectIcon" alt v-if="item.isSelect" />
                                            <img :src="noSelectIcon" alt v-else />
                                        </div>
                                    </div>
                                </div>
                                <div class="no-data" v-else>暂无数据</div>
                            </div>
                        </div>
                    </el-col>
                </el-row>
            </el-form-item>
        </el-form> 
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="handleClose">取消</el-button>
                <el-button type="primary" @click="submit()">确定</el-button>
            </span>
        </template>
    </el-dialog>
</template>
<script setup>
import api from "@/api/index";
import { ElMessage, ElMessageBox } from 'element-plus'
import selectIcon from '@/assets/images/check_select.png'
import noSelectIcon from '@/assets/images/check_no_select.png'
import { singleArr, treeData, unique } from '@/util/index'
import { useUserStore } from '@/store/index'
import { dataListStore } from '@/store/modules/pubiclDataList'
const props = defineProps({
    dialogVisible: {
        type: Boolean,
        default: false
    },
    nodeData: {
        type: Object,
        default: () => { }
    },

    budgetTemplateId: {
        //模板 id 预算编制使用
        type: String,
        default: ''
    }

})
const dataStore = dataListStore()

const dataForm = ref({
    subjectName: ''
})


const subjectList = ref([])

const pageData = ref({
    pageNum: 1,
    pageSize: 100,
    total: 0
})
const userStore = useUserStore()

const treeDatas = ref([])

const subjectOldDataList = ref([])

const formRef = ref(null)

const selectSubjectList = ref([])

const orgCodes = ref('')

const emit = defineEmits(['on-update', 'handleClose'])

const treeRef = ref(null)

const CONMPAYN_PROPS = {
    checkStrictly: true,
    label: 'name',
    value: 'id',
    children: 'children'
}

const selectNum = computed(() => {
    let list = []
    subjectList.value.forEach((item) => {
        if (item.isSelect) {
            list.push(item)
        } else {
            const findIndex = selectSubjectList.value.findIndex(itemTwo => itemTwo.id == item.id)
            if(findIndex>-1)  selectSubjectList.value.splice(findIndex,1)
        }
    })
    selectSubjectList.value = unique([...selectSubjectList.value,...list],'id')
    return list.length
})


onMounted(() => {
    const departmentId = userStore.userInfo.departmentVo?.departmentId
    orgCodes.value = departmentId
    if (props.budgetTemplateId && props.budgetTemplateId != '') {
        passTempleteIdQuerySubject()
       
    } else {
       
        getSubjectList(departmentId)
    }
    
});

// 通过模板 id 查询 科目 预算编制专用
const passTempleteIdQuerySubject = () => {
    api.budgetConfig.querySubject({ templateId: props.budgetTemplateId, pageNum: 1, pageSize:10000 }).then(res => {
        console.log('拿到科目数据', res)
        const { list } = res
        let newList = list.filter(item => item.enabled)
        newList.forEach(item => {
            item['isSelect'] = false
        })

        let result = arrUnique(newList)
        subjectList.value = result
        subjectOldDataList.value = result
    })
}

const getCompayTree = () => {

    const path = userStore.userInfo.departmentVo.path
    const pathArr = path.split("-")
    api.user.userGetConmpanyTree().then(res => {
        // 只能显示自己和自己以上的组织
        let arr = singleArr(res)
        let result = arr.filter(item => {
            if (path == `${item.parentId}-${item.id}` || (pathArr.includes(item.id))) {
                return item
            }
        })
        result.forEach(item => {
            if (item.children) {
                delete item.children
            }
        })
        treeDatas.value = treeData(result, 'id', 'parentId', '0')


    })
}
// 关闭
const handleClose = () => {
    formRef.value.resetFields()
    formRef.value.clearValidate()
    emit('handleClose')

}
// 全选
const allCheck = () => {
    let arr = subjectList.value.filter(item => item['isSelect'])
    if (arr.length == subjectList.value.length) {
        // 代表已全选 应该反选
        subjectList.value.forEach(item => {
            item['isSelect'] = false
        })
    } else {
        subjectList.value.forEach(item => {
            item['isSelect'] = true
        })
    }
}

// 选择科目
const selectSubject = (index) => {
    subjectList.value[index]['isSelect'] = !subjectList.value[index]['isSelect']
}

const removeTab = (val, item) => {
    console.log(val, item)
    var index = subjectList.value.findIndex(item2 => item2.categoryName == item.categoryName)
    console.log(index)
    if (index > -1) {
        subjectList.value[index]['isSelect'] = false
        selectSubjectList.value.splice(index, 1)
    }

}

// 选择节点 查询科目
const currentChange = (node, data) => {
    console.log(node, data)

    treeRef.value.setCheckedNodes([node])
    orgCodes.value = node.id
    getSubjectList(node.id)

}
// 获取科目数据
const getSubjectList = (orgCode) => {
    const parms = {
        ...pageData.value,
        orgCode
    }
    api.budgetConfig.budgetSubjectList(parms).then(res => {
        const { list } = res
        let newList = list.filter(item => item.enabled == true)
        newList.forEach(item => {
            item['isSelect'] = false
        })
        console.log(newList,'newListnewList')
     
        let result = arrUnique(newList)
        subjectList.value = result
        subjectOldDataList.value = result
    })
}

// 去重
const arrUnique = (list) => {
    let newList = []
    list.forEach(item => {
        let flag = false
        dataStore.selectAllSubjectList.forEach(allItem => {
            
            if (item.id == allItem.budgetCategoryId) flag = true
        })
        if (!flag) newList.push(item)

    })
    return newList
}


// 搜索科目
const searchSubject = (val) => {
    if (val == '') {
        subjectList.value = subjectOldDataList.value
    } else {
        console.log(subjectOldDataList.value)
        subjectList.value = subjectOldDataList.value.filter(item => item.categoryName.includes(val))
    }

}
const updateSubmit = (data) => {
    if (props.budgetTemplateId && props.budgetTemplateId != '') {
        let params = {
            budgetCategoryIds: data.map(item => item.id),
            templateId: props.budgetTemplateId
        }
        api.budgetConfig.budgetQuerySubject(params).then(res => {
            res.forEach((item) => {
                item.feeTypeRelationParams = item.feeTypeRelationDTOList
                item.isShowAddBtn = true
                item['isShowDelBtn'] = false
               item.addType ='del'
                 
                if (item.feeTypeRelationDTOList && item.feeTypeRelationDTOList.length == 0) item.isShowAddBtn = false
                item.id = null
                data.forEach((itemTwo, indexTwo) => {
                    if (item.budgetCategoryId == itemTwo.budgetCategoryId) {
                        item.label = itemTwo.label
                        item.categoryName = itemTwo.label
                        data.splice(indexTwo, 1)
                    }
                })

            })

            if (data.length > 0) {
                let msgStr = ''
                data.forEach(item => {
                    msgStr += item.label + '.'
                })
                ElMessageBox.alert(`${msgStr}不存在预算模板中`, '温馨提示', {
                    confirmButtonText: '我知道了',

                })
            }
            emit('on-update', res)
            handleClose()

        })
    } else {
        emit('on-update', data)
        handleClose()
    }
}
const submit = () => {
    if (!formRef) return
    formRef.value.validate(valid => {
        if (valid) {
            if (selectSubjectList.value.length == 0) return ElMessage.error('请选择科目')
            let children = []
          
            selectSubjectList.value.forEach(item => {
                console.log(item,'itemitem')
                let obj = {
                    "afterExceed": "",// 超标限制
                    "budgetCategoryId": item.id, // 当前科目的 id
                    "id": item.id,
                    "parentBudgetCategoryId": props.nodeData?.budgetCategoryId || null, // 上级 id
                    "templateId": null,
                    "feeTypeRelationParams": [], // 费用类型数据
                    "feeTypeVOList": [], // 费用类型数据
                    'label': item.categoryName,
                    'orgCode': orgCodes.value,
                    'addType': 'add',
                    categoryCode: item.categoryCode,
                    categoryName: item.categoryName
                }
                children.push(obj)
            })
            updateSubmit(children)
        

        } else {
            console.log('error submit!')
            return false
        }
    })
}



</script>
<style lang="scss" scoped>
.search-input {
    padding: 10px 0;
}

.tabs,
.head {
    display: flex;
    height: 40px;
    align-items: center;
    border-bottom: 1px solid #dcdfe6;
    width: 100%;
    border-right: 1px solid #dcdfe6;

    p {
        margin: 0;
        font-size: 14px;
        margin: 0 14px;
        cursor: pointer;

        &.active {
            color: #0049ad;
            border-bottom: 1px solid #0049ad;
        }
    }
}

.head {
    border-right: 0;

    p {
        &:nth-child(1) {
            padding-left: 10px;
            flex: 1;
            color: #0049ad;
        }

        &:nth-child(2) {
            text-align: right;
        }
    }
}

.city-box {
    padding-left: 10px;
    border-right: 1px solid #dcdfe6;
    padding-right: 10px;
}

.filter-tree {
    height: 340px;
    overflow-y: auto;
    padding-bottom: 20px;
}

.selec-city {
    padding: 10px 0;
    height: 400px;
    overflow-y: auto;
    padding-bottom: 20px;
}

.subject-con {
    .subject-list {
        margin: 0;
        display: flex;
        align-items: center;
        border-bottom: 1px solid #f5f5ff;
        padding: 0 10px;

        &:hover {
            background: #dcdfe6;
        }

        p {
            font-size: 14px;
            flex: 1;
            margin: 5px 0;
        }

        .check-box {
            img {
                width: 15px;
                height: 15px;
                margin-left: 15px;
                cursor: pointer;
            }
        }
    }
}

.tags {
    margin-right: 10px;
    margin-bottom: 10px;
}

.no-data {
    margin-top: 40px;
    text-align: center;
    color: #999;
    font-size: 14px;
}
</style>
